const router = require("koa-router")()

const fs = require("fs")

const path = require("path")

const db = require("../utils/db")

// 图片上传
const multer = require('@koa/multer');

router.prefix("/users")

// 获取数据
router.get("/get-users", async ctx => {
    // const sql = "select * from msbd where id = 407"
    // const r = await db.doSQL(sql)
    // ctx.body = db.doResponse({ message: "成功", data: r })

    // 获取数据的基本默认值
    const { pageSize = 5, currentPage = 0, query, sort = 'id', order = 'desc' } = ctx.query

    let sql = "select * from users"

    if (query) {
        sql += ` where name like '%${query}%'`
    }

    if (order) {
        sql += ` order by ${sort} ${order}`
    }

    if (pageSize) {
        sql += ` limit ${currentPage * pageSize},${pageSize}`
    }

    console.log(sql);

    let totalSql = "select count(*) as total from users"

    const totalr = await db.doSQL(totalSql)

    const total = totalr[0].total

    const r = await db.doSQL(sql)

    ctx.body = db.doResponse({ message: "成功", data: r, total })

})

// 新增
router.post("/add-users", async ctx => {
    const { name, age, gender, loginName, loginKey } = ctx.request.body
    const sql = "insert into users (name, age, gender, loginName, loginKey) values(?,?,?,?,?)"
    const params = [name, age, gender, loginName, loginKey]
    const r = await db.doSQL(sql, params)
    if (r.affectedRows > 0) {
        ctx.body = db.doResponse({ message: "成功", data: r })
    } else {
        ctx.body = db.doResponse({ message: "失败", errorCode: 4004, success: false, data: r })
    }
})

// 修改
router.post("/update-users", async ctx => {
    const { name, age, gender, loginName, loginKey, id } = ctx.request.body
    const sql = "update users set name=?,age=?,gender=?,loginName=?,loginKey=? where id=?"
    const params = [name, age, gender, loginName, loginKey, id]
    const r = await db.doSQL(sql, params)
    if (r.affectedRows > 0) {
        ctx.body = db.doResponse({ message: "成功", data: r })
    } else {
        ctx.body = db.doResponse({ message: "失败", errorCode: 4001, success: false, data: r })
    }
})

// 删除
router.get("/delete-users", async ctx => {
    const { id } = ctx.query
    const sql = `delete from users where id in (${id})`
    console.log(sql);
    const r = await db.doSQL(sql)
    console.log(r);
    if (r.affectedRows > 0) {
        ctx.body = db.doResponse({ message: "成功", data: r })
    } else {
        ctx.body = db.doResponse({ message: "失败", errorCode: 4005, success: false, data: r })
    }
})

// 图片上传
var storage = multer.diskStorage({
    //文件保存路径
    destination: function (req, file, cb) {
        // try {
        //     // 如果有这个文件夹，那就将图片存入这个文件夹
        //     fs.statSync(path.join(__dirname, "../public/upload"))
        // } catch (error) {
        //     // 如果没有文件夹就创建文件夹
        //     fs.mkdirSync("./public/upload")
        // }

        // try {
        //     fs.statSync(path.join(__dirname, '../public/upload-files'))
        // } catch (e) {
        //     fs.mkdirSync('./public/upload-files')
        // }

        cb(null, './public/upload-files')
    },
    //修改文件名称
    filename: function (req, file, cb) {
        var ext = (file.originalname).split(".").pop();
        cb(null, file.fieldname + "-" + Date.now() + "." + ext);
    }
})

//加载配置
var upload = multer({ storage })

// 单文件上传
// router.post("/upload", upload.single("avatar"), async ctx => {
//     // const { id } = ctx.request.body
//     // console.log(ctx.request.body);
//     // if (!id) {
//     //     ctx.body = db.doResponse({ message: "成功", data: ctx.request.file })
//     //     return
//     // }
// })

// 单文件域上传多文件
// router.post("/upload", upload.array("avatar", 3), ctx => {
//     ctx.body = "单文件域上传多文件"
// })

// 多文件域上传 
router.post("/upload", upload.fields([
    { name: "avatar", maxCount: 3 },
    { name: "pic", maxCount: 2 }
]), ctx => {
    ctx.body = "多文件域上传"
})

router.get("/form", ctx => {
    ctx.type = 'text/html;charset=utf-8'
    ctx.body = fs.createReadStream("./form/users.html")
})


module.exports = router